
import base64

import requests
import json

def get_access_token():

    api_key = 'K1OJt0so8k1MOy0wgmK5Q2tX'
    secret_key = 'zz5IxwIWL7tCwo5kgaGQUUbkrH9J56pZ'
    token_url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + api_key + '&client_secret=' + secret_key

    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", token_url, headers=headers, data=payload)

    print(response.text)

def invoice_recognition():
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice"
    # 二进制方式打开图片文件
    f = open('invoice1.jpg', 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    access_token = '24.fb0e6430b275dca6033c8b6e9b5b0166.2592000.1744450324.282335-118025493'# [调用鉴权接口获取的token]
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        print(response.json())

if __name__ == '__main__':
    '''
    获取api_key和secret_key
    获取access
    利用access进行添加参数，拼接出请求链接，拼接请求头进行发票识别
    '''
    # get_access_token()
    invoice_recognition()